<!--
 * @Description: ...
 * @Author: yangli 121029539@qq.com
 * @Date: 2025-02-06 11:23:56
 * @LastEditTime: 2025-02-19 14:17:40
 * @LastEditors: yangli 121029539@qq.com
 * @FilePath: \uniapp\src\pagesbaoxian\apply.vue
-->
<template>
    <view class="bg-page relative">
        <!--页面数据--->
        <view v-show="!state.showSignperson" class="">
            <view class="">
                <view class="mb-[20rpx] py-[32rpx] px-[20rpx] bg-white flex justify-between items-center">
                    <view class="text-main text-[32rpx] pb-[10rpx]">选择品牌</view>
                    <view @click="gotoSelectModel" class="text-[32rpx]">{{ state.brand ? state.brand : '请选择' }}
                        <u-icon name="arrow-right" color="#999" size="32" />
                    </view>
                </view>
                <view class="mb-[20rpx] py-[32rpx] px-[20rpx] bg-white flex flex-row justify-between items-center">
                    <view class="w-[300rpx]">
                        <view class="text-main text-[32rpx]">填写手机IMEI</view>
                    </view>
                    <view class="text-right flex-1 text-c5 text-base">
                        <u-input class="!text-right" v-model="state.formData.imei" placeholder="请输入" type="text" />
                    </view>
                </view>
                <view class="mb-[20rpx] py-[32rpx] px-[20rpx] bg-white flex flex-row justify-between items-center">
                    <view class="w-[300rpx]">
                        <view class="text-main text-[32rpx]">填写卡密</view>
                    </view>
                    <view class="text-right flex-1 text-c5 text-base">
                        <u-input class="!text-right" v-model="state.formData.card_pwd" placeholder="请输入" type="text" />
                    </view>
                </view>

                <view class="mb-[20rpx] py-[32rpx] px-[20rpx] bg-white flex flex-row justify-between items-center">
                    <view class="w-[300rpx]">
                        <view class="text-main text-[32rpx]">填写名字</view>
                    </view>
                    <view class="text-right flex-1 text-c5 text-base">
                        <u-input class="!text-right" v-model="state.formData.contacts_name" placeholder="请输入"
                            type="text" />
                    </view>
                </view>
                <view class="mb-[20rpx] py-[32rpx] px-[20rpx] bg-white flex flex-row justify-between items-center">
                    <view class="w-[300rpx]">
                        <view class="text-main text-[32rpx]">填写⼿机号</view>
                    </view>
                    <view class="text-right flex-1 text-c5 text-base">
                        <u-input class="!text-right" v-model="state.formData.contacts_phone" placeholder="请输入"
                            type="text" />
                    </view>
                </view>

                <view class="bg-white mb-[10px]">
                    <view class="p-[32rpx]">
                        <view class="mb-[20rpx]">
                            <view class="text-[36rpx] text-main font-extrabold">上传照片(请上传⼿机正⾯照⽚)</view>
                        </view>
                        <u-upload :custom-btn="true" :action="action_url" :show-progress="true" :maxCount="9"
                            :header="uploadHeader" :before-upload="onbeforeunload" @on-uploaded="onUploaded" width="160"
                            height="160">
                            <template v-slot:addBtn>
                                <view class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                                    <image class="w-[100px] h-[100px]" src="/static/images/repair/upload.png"></image>
                                </view>
                            </template>
                        </u-upload>
                        <view class="text-[30rpx] text-main pl-[40rpx] pt-[20rpx]">最少1张</view>
                    </view>
                </view>
                <view class="bg-white mb-[10px] p-[32rpx]" @click="showSignperson">
                    <view class="text-[36rpx] py-[20rpx] font-extrabold">签名 </view>
                    <!-- height="380rpx"  -->
                    <u-image width="100%" height="400rpx" :src="agreement.signImg" mode="widthFix">
                        <template v-slot:error>
                            <view style="font-size: 24rpx">点击生成签名</view>
                        </template>
                    </u-image>
                </view>
                <view class="bg-white mb-[10px]">
                    <view class="p-[32rpx]">
                        <view class="text-[24rpx] text-main font-extrabold pb-[20rpx]">请阅读如下协议并签字</view>
                        <view class="text-[20rpx] flex text-main">
                            <view class=" ">
                                <cc-protocolBox :agree="agreement.deductible_liability_agree" :protocolArr="['免赔责任']"
                                    @click="
                                        agreement.deductible_liability_agree =
                                        !agreement.deductible_liability_agree
                                        " @protocolClick="protocolClick"></cc-protocolBox>
                            </view>
                            <view>
                                <cc-protocolBox :agree="agreement.guarantee_agree" :protocolArr="['保障范围']"
                                    @click="agreement.guarantee_agree = !agreement.guarantee_agree"
                                    @protocolClick="guaranteeClick"></cc-protocolBox>
                            </view>
                            <view>
                                <cc-protocolBox :agree="agreement.privacy_agree" :protocolArr="['隐私政策']"
                                    @click="agreement.privacy_agree = !agreement.privacy_agree"
                                    @protocolClick="privacyClick"></cc-protocolBox>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <view class="py-[60rpx] px-[48rpx] btn-wrap">
                <u-button :disabled="disabled" :loading="isLock" @tap="onSubmit" type="primary">
                    兑换
                </u-button>
            </view>
        </view>
        <!--签名弹框--->
        <view v-show="state.showSignperson" style="background-color: #fff; border: 1px solid red; overflow: hidden">
            <piaoyi-signature @onSuccess="finishSignperson" />
        </view>
        <!--协议弹框--->

        <u-popup v-model="agreement.showModel" mode="center" :closeable="true" border-radius="16">
            <view class="w-[680rpx] p-[32rpx]">
                <view class="py-[20rpx] text-center text-[36rpx] font-extrabold">
                    {{ agreement.modelTitle }}</view>
                <view>
                    <scroll-view scroll-y="true" style="height: 900rpx">
                        <u-parse :html="agreement.modelConentet"></u-parse>
                    </scroll-view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script setup lang="ts">
import {
    insurancePolicyexchange,
    goodsDetail,
    apiGetSpecByImei,
    apiProductItemsBySpec,
    apisavesignimg
} from '@/api/repair'
import { onLoad, onShow, onPageScroll } from '@dcloudio/uni-app'
import { computed, reactive, ref, shallowRef } from 'vue'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { useLockFn } from '@/hooks/useLockFn'
import { getPolicy } from '@/api/app'

const finishSignperson = (res: any) => {
    state.showSignperson = false
    console.log(res)
    // agreement.signImg = res

    apisavesignimg({
        image: res
    }).then((res) => {
        agreement.signImg = res.url
    })
}
const showSignperson = () => {
    state.showSignperson = true
}

const gotoSelectModel = () => {
    uni.navigateTo({
        url: '/pages/model/model?from=exchange'
    })
}

const agreement = reactive({
    deductible_liability_agree: false,
    guarantee_agree: false,
    showModel: false,
    modelConentet: '',
    modelTitle: '',
    privacy_agree: false,
    signImg: ''
})

const guaranteeClick = (tag: any) => {
    getPolicy({ type: 'guarantee' }).then((res) => {
        agreement.showModel = true
        agreement.modelConentet = res.content
        agreement.modelTitle = res.title
    })
}
const protocolClick = (tag: any) => {
    getPolicy({ type: 'deductible_liability' }).then((res) => {
        agreement.showModel = true
        agreement.modelConentet = res.content
        agreement.modelTitle = res.title
    })
}

const privacyClick = (tag: any) => {
    getPolicy({ type: 'privacy_policy' }).then((res) => {
        agreement.showModel = true
        agreement.modelConentet = res.content
        agreement.modelTitle = res.title
    })
}

const payState = reactive({
    orderId: '',
    from: '',
    showPay: false,
    showCheck: false,
    redirect: '/pagesbaoxian/succ'
})

const appStore = useAppStore()
const userStore = useUserStore()
const token = computed(() => userStore.token)
const userInfo = computed(() => userStore.userInfo)
import { makeSign, uuid } from '@/utils/request/sign'

const disabled = computed(
    () =>
        !agreement.privacy_agree ||
        !agreement.guarantee_agree ||
        !agreement.deductible_liability_agree ||
        !agreement.signImg
)

const uploadHeader = reactive({
    token: token.value,
    nonce: uuid(),
    timestamp: 0,
    sign: ''
})

const fileList = ref([])
function onUploaded(lists: any) {
    fileList.value = lists
}
const action_url = `${import.meta.env.VITE_APP_BASE_URL}/api/upload/image`

const onbeforeunload = (file: any) => {
    uploadHeader.timestamp = Date.now()
    uploadHeader.sign = makeSign({}, uploadHeader.nonce, uploadHeader.timestamp)
}

const state = reactive({
    pageData: {
        id: '',
        name: '',
        img: ''
    },
    formData: {
        imei: '',
        card_pwd: '',
        product_id: [],
        contacts_name: '',
        contacts_phone: '',
        signImg: '',
        brand: ''
    },
    model_id: 0,
    produc_type_id: 0,
    brand: '',
    productList: [],
    currentStep: 1,
    select_list: [],
    check_file: false,
    showSignperson: false
})

const onSubmit = async () => {
    if (!token.value)
        return uni.showModal({
            title: '温馨提示',
            content: '当前账号未登录，无法提交',
            confirmText: '去登录',
            success: async (res) => {
                if (res.confirm) {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                }
            }
        })
    await applyLock()
}

const { isLock, lockFn: applyLock } = useLockFn(async () => {
    uni.showLoading({
        title: '加载中'
    })
    state.formData.signImg = agreement.signImg
    state.formData.brand = state.brand
    if (!state.formData.imei) return uni.$u.toast('请输入IMEI')
    if (!state.formData.card_pwd) return uni.$u.toast('请输入卡密')
    if (!state.formData.contacts_name) return uni.$u.toast('请输入联系人姓名')
    if (!state.formData.contacts_phone) return uni.$u.toast('请输入联系人手机号')

    let imgs: string[] = []
    if (fileList.value && fileList.value.length > 0) {
        fileList.value.map((file: any) => {
            if (file.response && file.response.data && file.response.data.uri) {
                imgs.push(file.response.data.uri)
            }
        })
    } else {
        return uni.$u.toast('请上传照片')
    }
    let postData = { ...state.formData, imgs }
    const data = await insurancePolicyexchange(postData)
    payState.orderId = data.order_id
    uni.hideLoading()
    uni.$u.toast('兑换成功')
    uni.switchTab({
        url: '/pages/index/insurance'
    })
})

onLoad((options: any) => {
    const modelInfo = appStore.getModel()
    if (modelInfo) {
        state.brand = modelInfo.name
    }
    state.formData.contacts_name = userInfo?.value.nickname
    state.formData.contacts_phone = userInfo?.value.mobile

})
</script>

<style lang="scss" scoped>
::v-deep {
    .u-btn--primary--disabled {
        background: #f6b997 !important;
    }
}
</style>
